package com.zdb.demo.design.pattern.behavioral.interpreter;

import java.util.Stack;

public class ExpressionParser {

    private Stack<Interpreter> stack = new Stack<>();

    public int parse(String str) {
        String[] strs = str.split(" ");
        for(String symbol : strs) {
            if(!OperatorUtil.isOperatorString(symbol)) {
                Interpreter numInterpreter = new NumberInterpreter(symbol);
                stack.push(numInterpreter);
                System.out.println("加入数字：" + numInterpreter.interpret());
            } else {
                Interpreter first = stack.pop();
                Interpreter second = stack.pop();
                Interpreter operator = OperatorUtil.getExpressionObject(first, second, symbol);
                int result = operator.interpret();
                stack.push(new NumberInterpreter(result));
                System.out.println("加入结果：" + result);
            }
        }


        return stack.pop().interpret();
    }

}
